<?php
    class util
    {
        public static function open_connection()
        {
            $con = null;
            include('config.php');
            $con = mysql_connect($db_server, $mysql_username, $mysql_password);
            mysql_select_db($db_name, $con);
            if (!$con)
            {
                die('Could not connect: ' . mysql_error());
            }
            return $con;
        }

        public static function close_connection($con)
        {
            mysql_close($con);
        }

        public static function get_function_cache($udnurl, $function_name)
        {
            $con = util::open_connection();

            $udnurl = mysql_real_escape_string($udnurl);
            $result = mysql_query("SELECT UNCOMPRESS(compresed_content) as content FROM function_cache where udnurl='$udnurl' and function_name = '$function_name'");
            $contents = null;

            while ($row = mysql_fetch_array($result))
            {
                $contents = $row['content'];
            }
            util::close_connection($con);
            return $contents;
        }

        public static function set_function_cache($udnurl, $function_name, $contents)
        {
            $con = util::open_connection();

            $udnurl = mysql_real_escape_string($udnurl);
            $escaped_contents = mysql_real_escape_string($contents);
            mysql_query("DELETE FROM function_cache WHERE udnurl='$udnurl' and function_name = '$function_name'");
            mysql_query("INSERT INTO function_cache (udnurl, function_name, compressed_content)
              VALUES ('$udnurl', '$function_name', COMPRESS('$escaped_contents'))");

            util::close_connection($con);
        }

        public static function get_sitemap_xpath($sitemap_meta_id)
        {
            $con = util::open_connection();
            $xpaths = null;
            $result = mysql_query("SELECT * FROM sitemap_meta where sitemap_meta_id = '$sitemap_meta_id'");

            while ($row = mysql_fetch_array($result))
            {
                $xpaths['image_xpath'] = $row['image_xpath'];
                $xpaths['description_xpath'] = $row['description_xpath'];
            }

            util::close_connection($con);
            return $xpaths;
        }

        public static function update_sitemap_data( $udnurl, $posterurl, $description)
        {
            $con = util::open_connection();

            $udnurl = mysql_real_escape_string($udnurl);
            $posterurl = mysql_real_escape_string($posterurl);
            $description = mysql_real_escape_string($description);

            mysql_query("UPDATE sitemap_data SET posterurl = '$posterurl', description = '$description'
              WHERE udnurl = '$udnurl'");

            util::close_connection($con);
        }
		
        public static function downloadFile ($url, $path)
        {
            $newfname = $path;
            $file = fopen ($url, "rb");
            if ($file) {
                $newf = fopen ($newfname, "wb");

                if ($newf)
                    while(!feof($file)) {
                        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
                    }
            }

            if ($file) {
                fclose($file);
            }

            if ($newf) {
                fclose($newf);
            }
        }

        public static function uncompressFile($url, $path) {
            $sfp = gzopen($url, "rb");
            $fp = fopen($path, "w");

            while ($string = gzread($sfp, 4096)) {
                fwrite($fp, $string, strlen($string));
            }
            gzclose($sfp);
            fclose($fp);
        }

        public static function get_filename_from_url($url)
        {
            $filename = str_replace('/', '-', $url);
            $filename = str_replace('http', '', $filename);
            $filename = str_replace('https', '', $filename);
            $filename = str_replace(':', '', $filename);
            $filename = str_replace('?', '', $filename);
            $filename = str_replace('=', '', $filename);
            $filename = str_replace('&', '', $filename);
            return $filename;
        }

        public static function make_title($title)
        {
            $title = urldecode($title);
            $title = str_replace('-',' ',$title);
            $title = ucwords($title);
            return $title;
        }

        public static function clean_url($string)
        {
            return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
        }

        public static function lastIndexOf($string,$item){
            $index=strpos(strrev($string),strrev($item));
            if ($index){
                $index=strlen($string)-strlen($item)-$index;
                return $index;
            }
            else
                return -1;
        }

        // disguises the curl using fake headers and a fake user agent.
        public static function read_url($url)
        {
            $curl = new Curl();
            $html = $curl->get($url);

            return $html;
        }

        //removes the first match
        public static function removeElement($domxPath, $xpath)
        {
            $domNodeList = $domxPath->query($xpath);
            if ($domNodeList->length > 0) {
                $domNode = $domNodeList->item(0);
                $domNode->parentNode->removeChild($domNode);
            }
        }

        //removes all matches
        public static function removeAllElements($domxPath, $xpath)
        {
            if ($domxPath->query($xpath)->length > 0)
                foreach ($domxPath->query($xpath) as $node)
                    $node->parentNode->removeChild($node);
        }

        public static function get_domain($url)
        {
            $parse = parse_url($url);
            return $parse['host']; // prints 'google.com'
        }

        public static function get_current_domain()
        {
            $domain = $_SERVER['SERVER_NAME'];
            if($domain == 'localhost') $domain = 'pcgamefind.com';
            return strtolower(str_replace('www','',$domain));
        }

        public static function add_domain_to_link($domain, $link)
        {
            if(substr($link,0,1) == '/')
            {
                return "http://".$domain.$link;
            }
            return $link;
        }
        public static function add_domain_to_link_by_url($url, $link)
        {
            $domain = util::get_domain($url);
            $newLink = util::add_domain_to_link($domain, $link);
            return $newLink;
        }

        public static function log_to_file($msg)
        {
            $date = date('d.m.Y h:i:s')."\r\n";
            include('include/config.php');
            error_log($date.$msg."\r\n", 3, $log_file);
        }


    }
    class Curl
    {

        public $cookieJar = "";

        public function __construct($cookieJarFile = 'cookies.txt')
        {
            $this->cookieJar = $cookieJarFile;
        }

        function setup()
        {


            $header = array();
            $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
            $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            $header[] = "Cache-Control: max-age=0";
            $header[] = "Connection: keep-alive";
            $header[] = "Keep-Alive: 300";
            $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
            $header[] = "Accept-Language: en-us,en;q=0.5";
            $header[] = "Pragma: "; // browsers keep this blank.


            curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($this->curl, CURLOPT_COOKIEJAR, $cookieJar);
            curl_setopt($this->curl, CURLOPT_COOKIEFILE, $cookieJar);
            curl_setopt($this->curl, CURLOPT_AUTOREFERER, true);
            curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
        }


        function get($url)
        {
            $this->curl = curl_init($url);
            $this->setup();

            return $this->request();
        }

        function getAll($reg, $str)
        {
            preg_match_all($reg, $str, $matches);
            return $matches[1];
        }

        function postForm($url, $fields, $referer = '')
        {
            $this->curl = curl_init($url);
            $this->setup();
            curl_setopt($this->curl, CURLOPT_URL, $url);
            curl_setopt($this->curl, CURLOPT_POST, 1);
            curl_setopt($this->curl, CURLOPT_REFERER, $referer);
            curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);
            return $this->request();
        }

        function getInfo($info)
        {
            $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);
            return $info;
        }

        function request()
        {
            $page = curl_exec($this->curl);
            curl_close($this->curl);

            return $page;
        }
    }
?>